<template>
    <section id="componentsContainer" v-loading="planLoading">
        <el-form ref="addFormRef" :model="addForm" inline :rules="addPlanRulesData">
            <el-form-item v-if="isCrm" label="签约审批单" prop="orderId" class="block">
                <el-select v-model="addForm.orderId" v-loading="isRemoteQuerying" remote-show-suffix
                    :disabled="isEditOrderId && !planId" :style="{ width: isEdit ? '580px' : '280px' }"
                    :loading="isRemoteQuerying" :remote-method="querySignList" filterable remote placeholder="请选择"
                    @change="onSignOrderChange">
                    <el-option v-for="item in signList" :key="item.applyCode" :label="item.label" :value="item.applyCode" />
                </el-select>
                <el-button v-if="!isEdit" type="primary" :disabled="!addForm.orderId.startsWith('WBQYD')" plain
                    @click="showJoinPlanPlays = true">
                    查看刊播信息
                </el-button>
            </el-form-item>

            <el-row>
                <el-form-item label="投放城市" prop="city">
                    <el-select v-model="addForm.city" :disabled="isEdit" filterable placeholder="请选择">
                        <el-option v-for="item in cityList" :key="item.cityCode" :label="item.city"
                            :value="item.cityCode" />
                    </el-select>
                </el-form-item>
                <el-form-item label="方案名称" prop="planName">
                    <el-input v-model="addForm.planName" :maxlength="20" placeholder="请输入"
                        :disabled="isEdit && planStatus === '003'" />
                </el-form-item>
                <el-form-item label="销售类型" prop="saleType">
                    <el-select v-model="addForm.saleType" :disabled="addForm.orderId.startsWith('WBQYD')" placeholder="请选择">
                        <el-option v-for="(item, key) in saleType" :key="key" :label="item" :value="key" />
                    </el-select>
                </el-form-item>
            </el-row>

            <el-row>
                <el-form-item label="行业" prop="trade">
                    <el-select v-model="addForm.trade" filterable :disabled="isEdit" placeholder="请选择">
                        <el-option v-for="(item, key) in secondTradeList" :key="key" :label="item.name"
                            :value="item.code" />
                    </el-select>
                </el-form-item>
                <el-form-item class="media-type-form" label="媒体类型" prop="mediaType">
                    <el-radio-group v-model="addForm.mediaType" :disabled="isEdit" @change="changeMediaType">
                        <el-radio :label="1" size="large">梯内屏</el-radio>
                        <el-radio :label="2" size="large">梯外屏</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="选点类型" prop="guaranteAmout">
                    <el-radio-group v-model="addForm.guaranteAmout" :disabled="isEdit">
                        <el-radio :label="0" size="large">选点保量</el-radio>
                        <el-radio :disabled="addForm.mediaType === 2" :label="4" size="large">选点不保量</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-row>

            <el-row>
                <el-form-item label="开始日期" prop="beginDate">
                    <el-date-picker v-model="addForm.beginDate" :disabled="isEdit" type="date" placeholder="选择日期"
                        :disabled-date="disabledBeginDate" value-format="YYYY-MM-DD" @change="handleBeginDateChanged" />
                </el-form-item>
                <el-form-item label="结束日期" prop="endDate">
                    <el-date-picker v-model="addForm.endDate" type="date" placeholder="选择日期"
                        :disabled-date="disabledEndDate" value-format="YYYY-MM-DD" />
                    <p v-if="totalDay" class="total-day">共：{{ totalDay }}天</p>
                </el-form-item>
                <el-form-item label="选点方式" prop="deliveryMode">
                    <el-select v-model="addForm.deliveryMode" :disabled="planStatus === '003' && isEdit" placeholder="请选择"
                        @change="onChangeDelieryMode">
                        <div v-if="addForm.mediaType === 1">
                            <el-option v-for="(item, key) in deliveryModeType" :key="key" :label="item" :value="key" />
                        </div>
                        <div v-if="addForm.mediaType === 2">
                            <el-option v-for="(item, key) in deliveryModeTypeOut" :key="key" :label="item" :value="key" />
                        </div>
                    </el-select>
                </el-form-item>
            </el-row>

            <el-row>
                <el-form-item label="时长" prop="seconds">
                    <el-select v-model="addForm.seconds" :disabled="isEdit" placeholder="请选择">
                        <el-option v-for="(item, key) in durationType" :key="key" :label="item" :value="key" />
                    </el-select>
                </el-form-item>
                <el-form-item label="频次" prop="numbers">
                    <el-select v-if="addForm.mediaType === 1" v-model="addForm.numbers" :disabled="isEdit"
                        placeholder="请选择">
                        <el-option v-for="(item, key) in numbersType" :key="key" :label="item" :value="key" />
                    </el-select>
                    <el-select v-if="addForm.mediaType === 2" v-model="addForm.numbers" :disabled="isEdit"
                        placeholder="请选择">
                        <el-option v-for="(item, key) in numbersTypeOut" :key="key" :label="item" :value="key" />
                    </el-select>
                </el-form-item>
                <el-form-item :disabled="isEdit" label="屏幕类型" prop="screenType">
                    <el-select v-model="addForm.screenType" :disabled="isEdit" placeholder="请选择">
                        <el-option v-for="(item, key) in planSreenType" :key="key" :label="item" :value="key" />
                    </el-select>
                </el-form-item>
            </el-row>

            <el-row class="row-wrap">
                <el-form-item label="签约点位数" prop="compactNum" class="columns">
                    <el-input v-model="addForm.compactNum" v-limitNumber="{ min: 0 }"
                        :disabled="planStatus === '003' && isEdit" :controls="false" :precision="0" :min="0"
                        placeholder="请输入" />
                    <section v-if="!isEdit" class="tips">
                        <span>说明</span><span class="content">：签约点位数 + 调剂点位数 = 方案可调度的点位数上限，当上限为0时，表示无限制</span>
                    </section>
                </el-form-item>
                <el-form-item label="调剂点位数" prop="regulateNum">
                    <el-input v-model="addForm.regulateNum" v-limitNumber="{ min: 0 }"
                        :disabled="planStatus === '003' && isEdit" :controls="false" :min="0" :precision="0"
                        placeholder="请输入" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="addForm.remark" :maxlength="100" placeholder="请输入" />
                </el-form-item>
            </el-row>

            <el-form-item class="block">
                <h4>上刊拍照要求</h4>
            </el-form-item>
            <el-form-item label="拍照方式" prop="photoUpReport">
                <el-select v-model="addForm.photoUpReport" placeholder="请选择"
                    :disabled="isEdit && planStatus === '003' && dayjs().isAfter(dayjs(addForm.beginDate), 'day')">
                    <el-option v-for="(item, key) in photoReportType" :key="key" :label="item" :value="key" />
                </el-select>
            </el-form-item>
            <el-form-item v-show="addForm.photoUpReport === '004'" label="拍照张数" prop="skPhotoNum">
                <el-input v-limitNumberBlur="{ min: 1, max: 15 }" v-model="addForm.skPhotoNum" type="number"
                    placeholder="15" />
            </el-form-item>
            <el-form-item label="是否带报" prop="photoUp">
                <el-select v-model="addForm.photoUp" :disabled="addForm.photoUpReport === '001'" placeholder="请选择">
                    <el-option v-for="(item, key) in photoType" :key="key" :label="item" :value="key" />
                </el-select>
            </el-form-item>
            <el-form-item class="block">
                <h4>下刊拍照要求</h4>
            </el-form-item>
            <el-form-item label="拍照方式" prop="photoDownReport">
                <el-select v-model="addForm.photoDownReport" placeholder="请选择"
                    :disabled="isEdit && planStatus === '003' && dayjs().isAfter(dayjs(addForm.endDate), 'day')">
                    <el-option v-for="(item, key) in photoReportType" :key="key" :label="item" :value="key" />
                </el-select>
            </el-form-item>
            <el-form-item v-show="addForm.photoDownReport === '004'" label="拍照张数" prop="xkPhotoNum">
                <el-input v-limitNumberBlur="{ min: 1, max: 15 }" v-model="addForm.xkPhotoNum" type="number"
                    placeholder="15" />
            </el-form-item>
            <el-form-item label="是否带报" prop="photoDown">
                <el-select v-model="addForm.photoDown" :disabled="addForm.photoDownReport === '001'" placeholder="请选择">
                    <el-option v-for="(item, key) in photoType" :key="key" :label="item" :value="key" />
                </el-select>
            </el-form-item>
        </el-form>
    </section>
    <el-drawer v-model="showJoinPlanPlays" :size="1000" title="查看刊播信息">
        <section class="tips">选中后，方案属性会默认使用所选刊播信息的属性，但依然可以修改</section>
        <XcTable width="100%" :data="joinPlanPlays" :columns="tableColumns">
            <template #radio="{ row }">
                <el-radio v-model="selectedPlayPlan" :label="row.planPlayId">{{ ` ` }} </el-radio>
            </template>
        </XcTable>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="showJoinPlanPlays = false">取消</el-button>
                <el-button type="primary" :disabled="!selectedPlayPlan" @click="handlePlayPlanConfirm">确认</el-button>
            </span>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, defineProps, watch } from 'vue';
import { getJoinSignApproval, savePlan, getPlanInfo } from '@/api/plan.ts';
import { debounce } from 'lodash';
import { useStore } from 'vuex';
import { addPlanRules } from './rules.ts';
import { getFormatDate, getProvinceAndCityFromRigions, validateForm, isBefore } from '@/utils/common.ts';
import { getSecondTradeList } from '@/api/plan.ts';
import useTableSetting from '@/hooks/useTableSetting.ts';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { useRoute } from 'vue-router';
import useCreatePlan from '../hooks/useCreatePlan.ts';
import {
    saleType,
    planSreenType,
    deliveryModeType,
    deliveryModeTypeOut,
    photoReportType,
    photoType,
    numbersType,
    numbersTypeOut,
    durationType,
    photoNumberMax,
} from '@/utils/config.ts';
import XcTable from '@x-tech/fe-pc-components/src/components/XcTableTemplate/XcTable.vue';

const props = defineProps({
    isEdit: {
        type: Boolean,
        default: false,
    },
    isCreate: {
        type: Boolean,
        default: false,
    },
    planId: {
        type: Number,
        default: () => null,
    },
});

console.log('isCreate:?', props.isCreate);
const store = useStore();
const route = useRoute();
const selectedPlayPlan = ref(null);
const isRemoteQuerying = ref(false);
const planLoading = ref(null);
const cityList = computed(() => store.state.userGroup.userInfo?.cityList);
const isCrm: any = computed(() => store.state.userGroup.userInfo?.useCrm);
const selectedCity = computed(() => store.state.userGroup.userInfo?.selectedCity);
const addFormRef = ref<FormInstance>();
const addPlanRulesData = reactive<FormRules>(addPlanRules);
const signList = ref([]);
const showJoinPlanPlays = ref(false);
const secondTradeList = ref([]);
const isEditOrderId = ref(false);
const applyCode = route.query.applyCode || null;
const planStatus = ref('');
const deliveryMode = ref('');
const regulateNum = ref('');
const compactNum = ref('');
const addForm = reactive({
    beginDate: '',
    city: selectedCity.value ? selectedCity.value : cityList.value[0].cityCode,
    compactNum: 0,
    deliveryMode: '001',
    endDate: '',
    numbers: '005',
    orderId: '',
    photoDown: '002',
    photoDownReport: '001',
    photoUp: '002',
    photoUpReport: '001',
    planId: '',
    planName: '',
    regulateNum: 0,
    remark: '',
    saleType: '001',
    screenType: '003',
    seconds: '001',
    trade: '',
    oldPlanId: '',
    mediaType: 1, // 0：未知  1梯内 2梯外
    guaranteAmout: 0, // "0:选点保量，4：不保量"
    skPhotoNum: 15,
    xkPhotoNum: 15,
});
const groupCode = computed(() => store.state.userGroup.userInfo?.groupCode);

const { planId } = useCreatePlan();

const totalDay = computed(() => {
    const { endDate, beginDate } = addForm;
    return dayjs(endDate).diff(beginDate, 'day') + 1;
});

const disabledBeginDate = (date: Date) => dayjs(date).isBefore(dayjs(), 'day');

// 如果开始时间大于结束时间，清空结束时间
const disabledEndDate = computed(() => {
    return (date: Date) => {
        const { beginDate } = addForm;
        if (props.isEdit) {
            if (dayjs(date).isBefore(dayjs(beginDate), 'day')) {
                return true;
            }
            if (dayjs(date).isAfter(addForm.endDate)) {
                return true;
            }
            // 在开始日期和结束日期之间的日期 再和当前日期比较 当前日期之前的日期 禁用
            if (dayjs(date).isSame(dayjs(new Date()).format("YYYY-MM-DD"), 'day')) {
                return false;
            }
            if (dayjs(date).isBefore(dayjs(new Date()).format("YYYY-MM-DD"), 'day')) {
                return true;
            }
        }
        return dayjs(date).isBefore(dayjs(beginDate), 'day');
    };
});

const handleBeginDateChanged = () => {
    const { endDate, beginDate } = addForm;
    const isBeginAfterEnd = dayjs(beginDate).isAfter(dayjs(endDate), 'day');
    if (isBeginAfterEnd) {
        addForm.endDate = null;
    }
};

watch(
    () => addForm.photoDownReport,
    (val) => {
        if (val === '001') {
            addForm.photoDown = '002';
        }
    }
);
watch(
    () => addForm.photoUpReport,
    (val) => {
        if (val === '001') {
            addForm.photoUp = '002';
        }
    }
);
watch(
    () => addForm.mediaType,
    (val) => {
        if (val === 2) {
            addForm.guaranteAmout = 0;
        }
    }
);
const deleted = computed(() => store.state.plan.deleted);
const handleGetPlanInfo = async () => {
    planLoading.value = true;
    try {
        const data = await getPlanInfo({ planId: props.planId || planId.value, deleted: deleted.value }) || {};
        planStatus.value = data.status;
        deliveryMode.value = data.deliveryMode;
        compactNum.value = data.compactNum;
        regulateNum.value = data.regulateNum;

        console.log('data: ', data);
        Object.keys(addForm).forEach((key) => {
            if (key in data) {
                addForm[key] = data[key];
                if (key === 'city') {
                    addForm[key] = +data[key];
                }
            }
        });
        if (isCrm.value) {
            signList.value = [
                {
                    label: data.orderName,
                    applyCode: data.orderId,
                },
            ];
        }
        isEditOrderId.value = !!data.orderId;
        !addForm.orderId && querySignList('', true);
    } finally {
        planLoading.value = false;
    }
};

if (props.isEdit || planId.value) {
    handleGetPlanInfo();
}

const tableColumns = [
    { label: '', key: 'radio', render: true, prop: { width: '100', fixed: 'left' } },
    { label: '投放城市', key: 'belongPlaceName', prop: { width: '130' } },
    { label: '开始时间', key: 'planPlayTimeBegin', prop: { width: '200' } },
    { label: '结束时间', key: 'planPlayTimeEnd', prop: { width: '200' } },
    { label: '签约点位数', key: 'pointNumber', prop: { width: '150' } },
    { label: '时长', key: 'specifications', prop: { width: '130' } },
    { label: '频次', key: 'frequency', prop: { width: '130' } },
    { label: '屏幕类型', key: 'screenTypeStr', prop: { width: '130' } },
];
const regionList: any = computed(() => getProvinceAndCityFromRigions(store.state.app.common.CommonList.regionList));
const getRemoteOptions = async () => {
    secondTradeList.value = await getSecondTradeList() || [];
};
const joinPlanPlays = computed(() => {
    const data = signList.value.find(({ applyCode }) => applyCode === addForm.orderId)?.joinPlanPlayRequestDTOS || [];
    return data.map((item) => ({
        ...item,
        specifications: `${item.specifications}秒`,
        frequency: `${item.frequency}次/天`,
        planPlayTimeBegin: getFormatDate(item.planPlayTimeBegin),
        planPlayTimeEnd: getFormatDate(item.planPlayTimeEnd),
        screenTypeStr: '联动',
        screenType: '003',
    }));
});

const querySignList = debounce(async (keywords = null, isFirstCall) => {
    const params = {
        joinTraderCode: groupCode.value,
        size: 10,
        keywords,
    };
    isRemoteQuerying.value = true;
    try {
        const data = await getJoinSignApproval(params) || [];
        signList.value = data.map((item) => ({
            ...item,
            label: `${item.brandName}-${item.applyCode}`,
        }));

        if (isFirstCall && applyCode && isCrm && signList.value.length) {
            addForm.orderId = signList.value[0].applyCode;
        }
    } finally {
        isRemoteQuerying.value = false;
    }
}, 200);

const onSignOrderChange = () => {
    const signOrderSelected = signList.value.filter((item) => {
        return item.applyCode === addForm.orderId;
    })[0];
    // 销售类型与签约单类型强关联：签约单类型为框架、框架下定版单、现金时，销售类型只能为现金
    if (
        [
            'dic-business-opportunity-type-001',
            'dic-business-opportunity-type-005',
            'dic-business-opportunity-type-006',
        ].includes(signOrderSelected.signType)
    ) {
        addForm.saleType = '001';
    }
    // 销售类型与签约单类型强关联：签约单类型为置换时，销售类型只能为置换
    if (['dic-business-opportunity-type-003'].includes(signOrderSelected.signType)) {
        addForm.saleType = '002';
    }
    // 销售类型与签约单类型强关联：签约单类型为试播时，销售类型只能为赠播
    if (['dic-business-opportunity-type-004'].includes(signOrderSelected.signType)) {
        addForm.saleType = '003';
    }
};

onMounted(() => {
    if (isCrm.value && !props.isEdit) {
        const keywords = applyCode ? applyCode : null;

        querySignList(keywords, true);
    }
});

const handleplayPlanChanged = (playInfo) => {
    addForm.beginDate = playInfo.planPlayTimeBegin;
    addForm.endDate = playInfo.planPlayTimeEnd;
    addForm.city = +playInfo.belongPlaceCode;
    addForm.compactNum = playInfo.pointNumber;
    addForm.screenType = playInfo.screenType;
    // addform.seconds =
    Object.keys(durationType).forEach((key) => {
        if (durationType[key] === playInfo.specifications) {
            addForm.seconds = key;
        }
    });
    Object.keys(numbersType).forEach((key) => {
        if (numbersType[key] === playInfo.frequency) {
            addForm.numbers = key;
        }
    });
};
const onChangeDelieryMode = (event: any) => {
    if (planStatus.value === '002' && props.isEdit) {
        if (parseInt(event) > parseInt(deliveryMode.value)) {
            addForm.deliveryMode = deliveryMode.value;
            ElMessage.error('选点方式修改错误');
        }
    }
};
const handlePlayPlanConfirm = () => {
    showJoinPlanPlays.value = false;
    const selected = joinPlanPlays.value.find(({ planPlayId }) => planPlayId === selectedPlayPlan.value);
    handleplayPlanChanged(selected);
    selectedPlayPlan.value = null;
};

const handleSubmit = async () => {
    await validateForm(addFormRef.value);

    if (planId.value) {
        addForm.oldPlanId = planId.value;
        addForm.planId = '';
    } else {
        addForm.oldPlanId = '';
    }

    const data = await savePlan({ ...addForm, deleted: deleted.value });
    store.commit('plan/setPlanId', data);
    store.commit('plan/setOrderId', addForm.orderId);
};
const { maxTableHeight, setTableMaxHeight } = useTableSetting({ id: 'componentsContainer', offsetBottom: 130 });

onMounted(() => getRemoteOptions());

defineExpose({
    handleSubmit,
});

const changeMediaType = (val: number) => {
    addForm.numbers = val === 1 ? '005' : '001';
};
</script>

<style scoped lang="scss">
.media-type-form {
    width: 280px;
}

.el-form {
    .row-wrap {
        align-items: flex-start;
    }

    .el-form-item {
        display: inline-flex;
        flex-direction: column;
        align-items: flex-start;
        vertical-align: top;
        margin-bottom: 24px;

        &.block {
            display: flex;
            margin: 0 0 16px;

            :deep(.el-form-item__content) {
                line-height: 1.3;
            }
        }

        &.columns {
            :deep(.el-form-item__content) {
                flex-direction: column;
                align-items: flex-start;
            }
        }

        :deep(.el-form-item__label) {
            line-height: 20px;
            margin-bottom: 5px;
            color: #333;
        }

        :deep(.el-date-editor),
        .el-input,
        .el-select,
        .el-input-number,
        :deep(.el-cascader),
        .tips {
            width: 280px;

            & + .el-button {
                margin-left: 20px;
            }
        }

        .el-input-number :deep(.el-input__inner) {
            text-align: left;
        }

        .tips {
            font-size: 13px;
            margin-top: 10px;
            line-height: 1.3;

            .content {
                color: var(--el-text-color-placeholder);
            }
        }

        .total-day {
            position: absolute;
            right: 0;
            top: -45px;
        }
    }
}

.el-drawer .tips {
    color: #999999;
    margin-bottom: 12px;
    margin-top: -10px;
}

.mr-10 {
    margin-right: 10px;
}

.spe {
    margin-right: 43px;
}
</style>
